<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const imageSrc = ref('')
const hint = ref('')
const bgType = ref('')
const eventChannel = ref()

const isComplete = ref(false)

const canvasY = ref(0)
const canvasHeight = ref(0)
const systemInfo = ref()

const base64 = ref('')
const tempPath = ref('')

async function onInit() {
    systemInfo.value = uni.getSystemInfoSync()
    canvasY.value = systemInfo.value.windowHeight / 5
    canvasHeight.value = canvasY.value * 3
    // canvasWidth.value = systemInfo.value.windowWidth / 4 * 3

    console.log(await uni.getDeviceInfo())
}

async function takePhoto() {
    // ifdef: MP-APIPAY
    my.createCameraContext('ca').takePhoto({
        quality: 'high',
        success: async (res: any) => {
            base64.value = await urlToBase64(res.tempImagePath) as string

            tempPath.value = res.tempImagePath
            imageSrc.value = `data:image/jpeg;base64,${base64.value}`
            isComplete.value = true
        },
        fail: (res: any) => {
            console.log('err', res)
        },
    })
    // endif
}

/**
 * 将指定路径的文件内容转换为Base64编码的字符串
 *
 * @param path 文件路径
 * @returns 返回Promise对象，成功时resolve为转换后的Base64编码字符串，失败时reject为错误信息
 */
function urlToBase64(path: string) {
    return new Promise((resolve, reject) => {
        uni.getFileSystemManager().readFile({
            filePath: path,
            encoding: 'base64',
            success: (res) => {
                resolve(res.data)
            },
            fail: (err) => {
                reject(err)
            },
        })
    })
}

/**
 * 打开相册并选择图片
 */
function onOpenAlbum() {
    uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: async (res) => {
            const base64 = await urlToBase64(res.tempFilePaths[0]) as string
            emitAndBack(base64, res.tempFilePaths[0])
        },
        fail: (res: any) => {
            console.log('err', res)
        },
    })
}

async function onConfirm() {
    emitAndBack(base64.value, tempPath.value)
}

function emitAndBack(base64: string, tempPath?: string) {
    eventChannel.value.emit('base64', {
        base64,
        tempPath,
    })
    uni.navigateBack()
}

function onRedo() {
    imageSrc.value = ''
    tempPath.value = ''
    isComplete.value = false
}

function onReady(e: any) {
    console.log(111, e)
}

function onError(e: any) {
    console.log(e.detail)
}

function onCancel() {
    uni.navigateBack({})
}

onLoad((options) => {
    hint.value = options?.hint || ''
    bgType.value = options?.bgType || ''
})

onMounted(() => {
    onInit()
    const instance = getCurrentInstance()?.proxy

    eventChannel.value = (instance as any)?.getOpenerEventChannel()
})
</script>

<template>
    <NavbarContainer>
        <view class="h-full w-full">
            <camera id="ca" class="fixed left-1/2 top-1/2 z-50 w-full transform -translate-1/2"
                    :style="{ height: `${systemInfo?.windowWidth * 0.63}` }" output-dimension="1080p" device-position="back"
                    flash="off" @error="onError" @ready="onReady" />
            <img v-if="bgType === 'front'" class="fixed left-1/2 top-1/2 z-50 w-full transform -translate-1/2"
                 :style="{ height: `${systemInfo?.windowWidth * 0.63}` }"
                 src="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/blueUsercdfb827b-a724-4062-8a18-a3afc5a8eff2.png"
                 alt="">
            <img v-if="bgType === 'back'" class="fixed left-1/2 top-1/2 z-50 w-full transform -translate-1/2"
                 :style="{ height: `${systemInfo?.windowWidth * 0.63}` }"
                 src="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/blueUserd5b39e66-d5bc-4253-8361-32a976364478.png"
                 alt="">
            <view class="h-full flex flex-1 flex-col">
                <view class="flex-1 bg-black bg-op-60">
                    <view class="pt-30% text-center text-primary font-bold">{{ hint }}</view>
                </view>
                <view class="flex items-center justify-evenly bg-black bg-opacity-60" :style="`height:${canvasY + 30}px`">
                    <view class="text-white" @click="onOpenAlbum">
                        相册
                    </view>
                    <view class="h-130rpx w-130rpx flex items-center justify-center rounded-full bg-primary text-white"
                          @click="takePhoto">
                        拍照
                    </view>
                    <view class="text-white" @click="onCancel">
                        取消
                    </view>
                </view>
            </view>
        <!-- <img v-if="imageSrc" class="fixed left-1/2 top-1/2 z-230 w-full transform -translate-1/2"
             :style="{ height: systemInfo.windowWidth * 0.63 }" :src="imageSrc"> -->
        <!-- <canvas v-if="showCanvas" id="myCanvas" canvas-id="myCanvas" class="fixed left-0 top-0 z-250"
                :width="canvasWidth" :height="canvasHeight" /> -->
        <!-- <canvas id="myCanvas" canvas-id="myCanvas"
                class="fixed left-0 top-0 w-full border-1 border-red border-solid"
                :style="{ height: `${systemInfo?.windowWidth * 0.63}` }" /> -->
        </view>
        <view v-if="isComplete" class="fixed left-0 top-0 z-100 h-full w-full flex justify-center bg-black">
            <img class="fixed left-1/2 top-1/2 z-200 w-full transform -translate-1/2"
                 :style="{ height: `${systemInfo?.windowWidth * 0.63}` }" :src="imageSrc">
            <view class="fixed bottom-0 left-0 box-border h-200rpx w-full flex justify-between bg-black px-100rpx">
                <view class="h-120rpx w-120rpx flex items-center justify-center rounded-full bg-primary text-white"
                      @click="onRedo">
                    重拍
                </view>
                <view class="h-120rpx w-120rpx flex items-center justify-center rounded-full bg-primary text-white"
                      @click="onConfirm">
                    完成
                </view>
            </view>
        </view>
    </NavbarContainer>
</template>

<style lang="scss" scoped></style>

<route lang="json">
{}
</route>
